package com.lm.xstream.converter;

import com.lm.xstream.ele.Person2;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class PersonConverter implements Converter {

    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        Person2 person = (Person2) source;
        writer.startNode("name");
        writer.setValue(person.getName());
        writer.endNode();

        writer.startNode("age");
        writer.setValue(String.valueOf(person.getAge()));
        writer.endNode();
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        String name = null;
        int age = 0;

        while (reader.hasMoreChildren()) {
            reader.moveDown();
            String nodeName = reader.getNodeName();
            if ("name".equals(nodeName)) {
                name = reader.getValue();
            } else if ("age".equals(nodeName)) {
                age = Integer.parseInt(reader.getValue());
            }
            reader.moveUp();
        }

        return new Person2(name, age);
    }

    @Override
    public boolean canConvert(Class aClass) {
        return Person2.class.isAssignableFrom(aClass);
    }
}